package com.simple.controller;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.simple.entity.SysTable;
import com.simple.utils.GenerateUtils;
import com.simple.utils.MyStringUtils;
import com.simple.utils.TableUtils;

/**
 * 代码生成
 * 
 */
@Controller
@RequestMapping("/user")
public class SysCodeGenerationController {
	
	private static final Logger logger = LoggerFactory.getLogger(SysCodeGenerationController.class);

	//数据库名
	@Value("${generate.database}")
	String databaseName;
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	Connection connection;
	
	@RequestMapping("/sysCodeGeneration.html")
	public String sysCodeGeneration(Model model) {
		List<String> tableNameList = new ArrayList<>();
		javax.sql.DataSource dataSource=jdbcTemplate.getDataSource();
		try {
			connection=dataSource.getConnection();
			DatabaseMetaData dbMetaData = connection.getMetaData();			//从元数据中获取到所有的表名		
			ResultSet rs = dbMetaData.getTables(databaseName, null, null,new String[] { "TABLE" });
			while(rs.next()){		
				logger.info("表名: "+rs.getString("TABLE_NAME"));		
				tableNameList.add(rs.getString("TABLE_NAME"));		
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		model.addAttribute("tableNameList", tableNameList);
		return "sysCodeGeneration";
	}
	
	//数据表选择  获取表信息
	@RequiresPermissions("sysCodeGeneration:view")
	@RequestMapping("/sysCodeGeneration/sysTableSelect.html")
	@ResponseBody
	public JSONObject sysTableSelect(@RequestParam("tableName")String tableName){
		List<SysTable> list=new ArrayList<SysTable>();
		String sql="SHOW FULL COLUMNS FROM  "+tableName;
		 try {
			 PreparedStatement ps = connection.prepareStatement(sql);
			 ResultSet resultSet = ps.executeQuery();
			 while (resultSet.next()) {
				 SysTable sysTable=new SysTable();
				 String columnName=resultSet.getString("Field");//列名
				 String columnTypeName=resultSet.getString("Type");//列类型
				 String columnComment=resultSet.getString("Comment");//注释
				 if(columnTypeName.equals("int")) {
					 sysTable.setColumnEntityTypeName("Integer");
				 }else if(columnTypeName.contains("varchar")) {
					 sysTable.setColumnEntityTypeName("String");
				 }else if(columnTypeName.equals("datetime")) {
					 sysTable.setColumnEntityTypeName("Date");
				 }
				 sysTable.setColumnName(columnName);
				 sysTable.setColumnTypeName(columnTypeName);
				 sysTable.setColumnEntityName(MyStringUtils.lowerNameToEntity(columnName, false));
				 sysTable.setColumnComment(columnComment);
				 list.add(sysTable);
	         }
			// redisUtil.setValue(tableName,list);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return TableUtils.tableResult(list);
	}
	
	//代码生成
	@RequiresPermissions("sysCodeGeneration:edit")
	@RequestMapping("/sysCodeGeneration/codeGenerate.html")
	@ResponseBody
	public Map<String,Object> codeGenerate(HttpServletRequest request) {
		Map<String,Object>map=new HashMap<String, Object>();
		String tableData=request.getParameter("tableData");
		String tableName=request.getParameter("tableName");
		String title=request.getParameter("title");
		String isHtml=request.getParameter("isHtml");
		try {
			JSONObject jsonObject = JSONObject.parseObject(tableData);
			logger.info("-->表格数据JOSN:"+jsonObject.toString());
			JSONArray data=(JSONArray) jsonObject.get("data");
			List<SysTable> list=JSONObject.parseArray(data.toJSONString(), SysTable.class);
			//生成文件
			GenerateUtils.generateFile(list, tableName,databaseName,title,isHtml);
			map.put("status", 200);	
		} catch (Exception e) {
			map.put("status", 500);	
		}
		return map;
	}
}
